Ch8 Common collections
2026-09-25 ใน The rust programming language 3rd edition(online document)Vectors
let a = vec![1,2,3,4];
let b:Vec<i32>=Vec::new();
- The true form of Vector is a Structure type. So when you define vector, you can use Vec::new() function, just like defining any new structure.
2026-10-04 13:50
String
- Rust stores string in 3 types: vector of u8(eg. 'e'=[101]), char ['ก',' ็'], grapheme cluster['ส', 'วั', 'ส', 'ดี']
- Rust mostly doesn't allow to call String by index because most UTF-8 characters have 2-4 bytes which require 2-4 index to work properly.
- The better way is calling it by character, grapheme by combining it with
forand method.chars()and.bytes()
for c in "สวัสดี".chars(){
println!("{c}");
}
for c in "สวัสดี".bytes(){
println!("{c}");
}HashMap
- HashMap type is the
key:valuestorage of data - It's not use so much, so it's not on a default command lists in the std library, but can be used by defining it with
usecommand
use std::collections::HashMap;
let mut scores=HashMap::new();
scores.insert(String::from('blue'), 10);
scores.insert(String::from('red'), 20);
for(key, value) in scores{
println!("{key}:{value}");
}
- when add the data to the existing key, it will be automatically replaced by the new value
scores.insert(String::from('blue'),10);
scores.insert(String::from('blue'),30);โจทย์ท้ายบท
- Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list.
fn main(){
use std::collections::HashMap;
let mut a=vec![1,10,1,1,1,1,2,3,6,11,2,3,4,5,5,5,7,6,10,9,2,3];
let len=a.len();
sort(&mut a);
for i in 0..len{
print!("{} ",a[i]);
}
let mid=len/2;
let mut median:f32= a[mid] as f32;
if len % 2 == 0{
median=(a[mid]+a[mid+1]) as f32/2.0;
}
println!("\nLength = {}, Median = {}",len, median);
let mut b=HashMap::new();
for i in &a{
let count = b.entry(i).or_insert(0);
*count+=1;
}
let mut max_count=0;
let mut mode=0;
for (key, value) in &b{
if *value > max_count{
max_count = *value;
mode = **key as i32;
}
}
println!("Mode = {} count = {}",mode, max_count);
for i in 0..1{
println!("hello world")
}
}
fn sort(v:&mut Vec<i32>){
let len=v.len();
let mut temp;
for i in 0..(len){
for j in 0..(len-1-i){
if v[j]>v[j+1]{
temp=v[j+1];
v[j+1]=v[j];
v[j]=temp;
}
}
}
}
-
Convert strings to Pig Latin. The first consonant of each word is moved to the end of the word and ay is added, so first becomes irst-fay. Words that start with a vowel have hay added to the end instead (apple becomes apple-hay). Keep in mind the details about UTF-8 encoding!
-
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company; for example, “Add Sally to Engineering” or “Add Amir to Sales.” Then, let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.